package cn.wolfcode.mq;


import cn.wolfcode.ws.WebSocketServer;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "MQOrderResultListener",
        topic = MQConstant.ORDER_RESULT_TOPIC
)
public class MQOrderResultListener implements RocketMQListener<OrderMQResult> {

    @SneakyThrows
    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        log.info("进入到通知消费者中...");

        try {
            Thread.sleep(1000); // 睡一秒.避免消费者MQOrderCreateListener处理完毕业务, 发送消息给此类时,
                                        // WebSocketServer 还未建立连接, 导致消息不能被消费,即不能推送给用户
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // maven 中引入 websoceket 模块, 获取 webSocket 通信对象
        WebSocketServer webSocketServer = WebSocketServer.clients.get(orderMQResult.getToken());
        if (webSocketServer != null){
            try {
                log.info("发送消息给用户...");
                // 发送 orderMQResult 消息给用户
                webSocketServer.getSession().getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
